//
//  MDHSensitiveWordTools.m
//  MMWPT
//
//  Created by 高得华 on 2019/10/15.
//  Copyright © 2020 华&梅. All rights reserved.
//

#import "MDHSensitiveWordTools.h"

static NSString * const EXIST = @"isExists";

@interface MDHSensitiveWordTools()

@property (nonatomic, strong) NSMutableDictionary * root;

@property (nonatomic, strong) NSMutableArray * rootArray;

@property (nonatomic, assign) BOOL isFilterClose;

@end

@implementation MDHSensitiveWordTools

static MDHSensitiveWordTools * instance;

- (NSMutableArray *)rootArray{
    
    if (!_rootArray) {
        _rootArray = [NSMutableArray array];
    }
    return _rootArray;
}

+ (instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}

//复写init方法
- (instancetype)init {
    
    if (self) {
        self = [super init];
        //加载本地文件
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"minganci_ios" ofType:@"txt"];
        [self initFilter:filePath];
        
    }
    return self;
}

#pragma mark-加载本地敏感词库
/*
 * 加载本地的敏感词库
 *
 * @params filepath 敏感词文件的路径
 *
 */
- (void)initFilter:(NSString *)filepath{
    
    self.root = [NSMutableDictionary dictionary];

    NSString * fileString = [[NSString alloc] initWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
    [self loadFilter:fileString];
}

///加载敏感词库
- (void)loadFilter:(NSString *)data {
    [self loadFilter:data key:@"\r\n"];
}
- (void)loadFilter:(NSString *)data key:(NSString *)separator {
    [self.rootArray removeAllObjects];
    [self.rootArray addObjectsFromArray:[data componentsSeparatedByString:separator]];

    for (NSString *str in self.rootArray) {
        //插入字符，构造节点
        [self insertWords:str];
    }
}

-(void)insertWords:(NSString *)words{
    NSMutableDictionary *node = self.root;
    
    for (int i = 0; i < words.length; i ++) {
        NSString *word = [words substringWithRange:NSMakeRange(i, 1)];
        if (node[word] == nil) {
            node[word] = [NSMutableDictionary dictionary];
        }
        node = node[word];
    }
    
    //敏感词最后一个字符标识
    node[EXIST] = [NSNumber numberWithInt:1];
}

//MARK: -将文本中含有的敏感词进行替换
/*
 * 将文本中含有的敏感词进行替换
 *
 * @params str 文本字符串
 *
 * @return 过滤完敏感词之后的文本
 *
 */
- (NSString *)filter:(NSString *)str{
    
    ///是否包含
    BOOL is_bh = true;
    for (NSString * word in self.rootArray) {
        if ([str containsString:word]) {
            is_bh = false;
            break;
        }
    }
    
    if (self.isFilterClose || !self.root || is_bh) {
        return str;
    }
    
    NSMutableString *result = result = [str mutableCopy];
    
    for (int i = 0; i < str.length; i ++) {
        NSString *subString = [str substringFromIndex:i];
        NSMutableDictionary *node = [self.root mutableCopy];
        int num = 0;
        
        for (int j = 0; j < subString.length; j ++) {
            NSString *word = [subString substringWithRange:NSMakeRange(j, 1)];
            
            if (node[word] == nil) {
                break;
            }else{
                num ++;
                node = node[word];
            }
            
            //敏感词匹配成功
            if ([node[EXIST]integerValue] == 1) {
                
                NSMutableString *symbolStr = [NSMutableString string];
                for (int k = 0; k < num; k ++) {
                    [symbolStr appendString:@"*"];
                }
                
                [result replaceCharactersInRange:NSMakeRange(i, num) withString:symbolStr];
                
                i += j;
                break;
            }
        }
    }
    
    return result;
}

- (void)freeFilter {
    self.root = nil;
}

- (void)stopFilter:(BOOL)b {
    self.isFilterClose = b;
}

#pragma mark-判断文本中是否含有敏感词
/*
 * 判断文本中是否含有敏感词
 *
 * @params str 文本字符串
 *
 * @return 是否含有敏感词
 *
 */
- (BOOL)hasSensitiveWord:(NSString *)str{
    
    if (self.isFilterClose || !self.root) {
        return false;
    }
    
    NSMutableString *result = result = [str mutableCopy];
    
    for (int i = 0; i < str.length; i ++) {
        NSString *subString = [str substringFromIndex:i];
        NSMutableDictionary *node = [self.root mutableCopy] ;
        int num = 0;
        
        for (int j = 0; j < subString.length; j ++) {
            NSString *word = [subString substringWithRange:NSMakeRange(j, 1)];
            
            if (node[word] == nil) {
                break;
            }else{
                num ++;
                node = node[word];
            }
            
            //敏感词匹配成功
            if ([node[EXIST]integerValue] == 1) {
                return true;
            }
        }
    }

    return false;
}


@end
